//
//  AILDCalendar.m
//  carcareIOS
//
//  Created by ileo on 15/6/5.
//  Copyright (c) 2015年 baozun. All rights reserved.
//

#import "AILDCalendar.h"
#import "CalendarMgr.h"

@implementation AILDCalendar


- (instancetype)init
{
    self = [super init];
    if (self) {
        self.dbCalendarWay = [[DBCalendarWay alloc] init];
    }
    return self;
}

-(void)updateLocalData{
    [_dbCalendarWay reCreateTable];
    self.lastSavedYear = 0;
    self.lastSavedMonth = 0;
    self.lastLoadedDay = @"";
}

-(BOOL)needAutoSaveUserDefaultForProperty:(Property *)property{
    if ([property.name isEqualToString:@"dbCalendarWay"]) {
        return NO;
    }
    return YES;
}

-(void)updateSavedMonthWithYear:(NSInteger)year month:(NSInteger)month{
    NSInteger currentDay = CALENDARMGR.day;
    
    NSInteger savedYear = CALENDARMGR.year;
    NSInteger savedMonth = CALENDARMGR.month;
    
    if (savedYear == year && savedMonth == month) {
        self.lastLoadedDay = CALENDARMGR.currentDay;
    }
    
    if (currentDay - 7 <= 0) {
        savedMonth -= 2;
    }else{
        savedMonth--;
    }
    if (savedMonth <= 0) {
        savedMonth += 12;
        savedYear--;
    }
    
    self.lastSavedYear = MIN(savedYear, year);
    self.lastSavedMonth = MIN(savedMonth, month);
}

-(BOOL)needLoadFromNetWithYear:(NSInteger)year month:(NSInteger)month{
    if ([self.lastLoadedDay isEqualToString:[NSString stringWithFormat:@"%zd-%02zd-%02zd",year,month,CALENDARMGR.day]]) {
        return NO;
    }
    return (year > self.lastSavedYear) ||
          (year == self.lastSavedYear && month > self.lastSavedMonth);
}

@end

@implementation TriggerCalender

-(void)triggerByAccountUpdate{
    [[[AILDCalendar alloc] init] updateLocalData];
}

-(void)triggerByVersionUpdate{
    [[[AILDCalendar alloc] init] updateLocalData];
}

@end
